package com.hsy.directseeding.main.player;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deparse.dpframe.utils.DPLogUtil;
import com.hsy.directseeding.R;
import com.hsy.directseeding.common.CommonBaseActivity;
import com.hsy.directseeding.utils.CommonUtils;
import com.pili.pldroid.player.widget.VideoView;

import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * Created by Administrator on 2016/9/13.
 */
public class PlayerVideoActivity extends CommonBaseActivity {
    private VideoView videoPlayView;
    private MediaController videoPlayController;
//    private TextView videoPlayLogTextView;

    public PlayerVideoActivity() {
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 1) {
                DPLogUtil.d("42342344333333333333333");
                PlayerVideoActivity.this.initLayout();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        CommonUtils.showProgressDialog(this);
//        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            DPLogUtil.d("横向");
// WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
//            handler.sendEmptyMessage(1);

        } else {
            DPLogUtil.d("竖向");

        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏

        this.setContentView(R.layout.activity_player_video);
        setRightButtonVisiblity(View.VISIBLE);
        setRightButtonText("隐藏");
        setRightButtonTextColor(R.color.white);
        RelativeLayout layout = (RelativeLayout) this.findViewById(R.id.pili_videoview_fixed_layout);
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActionBarContainer().getVisibility() == View.GONE) {
                    getActionBarContainer().setVisibility(View.VISIBLE);
                }
            }
        });
//        this.initLayout();
        this.initVideoPlay();
    }

    @Override
    public boolean onActionBarRightButtonClicked(ImageButton rightButton) {
        getActionBarContainer().setVisibility(View.GONE);

        return super.onActionBarRightButtonClicked(rightButton);
    }

    private void initLayout() {
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        RelativeLayout layout = (RelativeLayout) this.findViewById(R.id.pili_videoview_fixed_layout);
        int width = dm.widthPixels;
        int height = width * 360 / 640;
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height);
        layout.setLayoutParams(layoutParams);
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActionBarContainer().getVisibility() == View.GONE) {
                    getActionBarContainer().setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void initVideoPlay() {
        this.videoPlayController = new MediaController(this);
        this.videoPlayView = (VideoView) this
                .findViewById(R.id.simple_video_play_pldplayer);
//        this.videoPlayLogTextView = (TextView) this
//                .findViewById(R.id.simple_video_play_log_textview);
//        videoPlayView.setMediaController(videoPlayController);
//        videoPlayController.setMediaPlayer(videoPlayView);
//        videoPlayController.setAnchorView(videoPlayView);
        final String videoName = this.getIntent().getStringExtra("videoName");
//        final String adsUrl = this.getIntent().getStringExtra("AdsUrl");
        final String videoUrl = this.getIntent().getStringExtra("videoUrl");
        this.setTitle(videoName);

        final long startTime = System.currentTimeMillis();

        //common settings
        videoPlayView.setOnErrorListener(new IMediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                boolean b = false;
//                videoPlayLogTextView.append("Play " + mp.getDataSource() + "Error, Pos" + mp.getCurrentPosition() + "\r\n");
                DPLogUtil.d("onError  what=" + what + "extra=" + extra);
                switch (extra) {
                    case IMediaPlayer.MEDIA_ERROR_UNKNOWN:
                        showToast("未知错误");
                        break;
                    case -2:
                        showToast("无效的URL");
                        break;
                    case -5:
                        showToast("网络异常");
//                        mp.release();
//                        finish();
                        b = true;
                        break;
                    case -11:
                        showToast("与服务器连接断开");
                        break;
                    case -111:
                        showToast("服务器拒绝连接");
                        break;
                    case -110:
                        showToast("连接超时");
                        break;
                    case -2001:
                        showToast("播放器准备超时");
                        break;
                    case -2002:
                        showToast("读取数据超时");
                        break;
                    case -875574520:
                        showToast("播放资源不存在");
//                        mp.release();
//                        finish();
                        b = true;
                        break;
                    default:
                        break;
                }
                CommonUtils.hideProgressDialog();
                return b;
            }
        });
        videoPlayView.setOnInfoListener(new IMediaPlayer.OnInfoListener() {

            @Override
            public boolean onInfo(IMediaPlayer mp, int what, int extra) {
//                videoPlayLogTextView.append("Play " + mp.getDataSource() + ", Pos:" + mp.getCurrentPosition() + "\r\n");
                DPLogUtil.d("onInfo  what=" + what + "extra=" + extra);
                if (IMediaPlayer.MEDIA_INFO_BUFFERING_START == what) {//开始缓冲
                    CommonUtils.showProgressDialog(PlayerVideoActivity.this);

                } else if (IMediaPlayer.MEDIA_INFO_BUFFERING_END == what) {//停止缓冲
                    CommonUtils.hideProgressDialog();
                }


                return false;
            }
        });

        if (!videoUrl.isEmpty()) {
            ///////////////// Play the ads first /////////////////////////

            videoPlayView.setVideoURI(Uri.parse(videoUrl));
            videoPlayView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(IMediaPlayer mp) {
                    long duration = videoPlayView.getDuration();
                    long endTime = System.currentTimeMillis();
                    long loadTime = endTime - startTime;
                    CommonUtils.hideProgressDialog();
//                    videoPlayLogTextView.append("Load Ads Time: "
//                            + Tools.formatMilliSeconds(loadTime) + ", Duration: " + duration + "ms\r\n");
                    DPLogUtil.d("onPrepared  ");
                    mp.start();
                }
            });


            //////////////////Play the video then ////////////////////////

            //video to play
            videoPlayView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(IMediaPlayer mp) {
                    videoPlayView.setVideoURI(Uri.parse(videoUrl));
                    final long startTime2 = System.currentTimeMillis();
                    CommonUtils.hideProgressDialog();
                    DPLogUtil.d("onCompletion ");
                    videoPlayView.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {

                        @Override
                        public void onPrepared(IMediaPlayer mp) {
                            long duration = videoPlayView.getDuration();
                            long endTime = System.currentTimeMillis();
                            long loadTime = endTime - startTime2;
                            DPLogUtil.d("onCompletion  onPrepared");
//                            videoPlayLogTextView.append("Load Video Time: "
//                                    + Tools.formatMilliSeconds(loadTime) + ", Duration:" + duration + "ms\r\n");
                            mp.start();
                        }
                    });
                    videoPlayView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {

                        @Override
                        public void onCompletion(IMediaPlayer iMediaPlayer) {
                            DPLogUtil.d("onCompletion  onCompletion");
//                            videoPlayLogTextView.append("All Play Ends\r\n");
                        }
                    });
                }
            });
        } else {
            showToast("暂无直播");
            DPLogUtil.d("null");
        }
    }
}
